package DesginFotmat;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class OutputInturn {
    /**
     * 交替输出
     * 线程1输出a5次，线程2输出b5次，线程3输出c5次
     * 现在要求输出abc/abc/abc/abc/abc
     */
    public static void main(String[] args) {
        WaitNotify waitNotify = new WaitNotify(1,6);
        Thread t1 = new Thread(() -> {
            waitNotify.print("a",1,2);
        },"t1");

        Thread t2 = new Thread(() -> {
            waitNotify.print("b",2,3);
        },"t2");

        Thread t3 = new Thread(() -> {
            waitNotify.print("c",3,1);
        },"t3");

        t1.start();
        t2.start();
        t3.start();
    }
}

/**
 * 输出内容         等待标记    下一个标记
 * a                1           2
 * b                2           3
 * c                3           1
 */
class WaitNotify{
    public void print(String str,int waitFlag,int nextFlag){
        for (int i = 0; i < loopNumber; i++) {
            synchronized (this) {
                while(flag!=waitFlag){
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                System.out.println(str);
                flag = nextFlag;
                this.notifyAll();
            }
        }
    }

    //等待标记
    private int flag;
    //循环次数
    private int loopNumber;
    public WaitNotify(int flag, int loopNumber) {
        this.flag = flag;
        this.loopNumber = loopNumber;
    }
}